<style lang="scss">
  /* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
  @import 'uview-ui/index.scss';
</style>
<script>
  import programSetting from '@/utils/programSetting.js'
  import commonFunction from '@/utils/commonFunction.js'
	import commonMorefunLogs from "@/utils/commonMorefunLogs.js"
  const cl_tracker = api.environment == 'trial' ? require('./utils/trial_cl_tracker.js') : require(
    './utils/cl_tracker.js');
  import customize from '@/utils/customize';
  import api from '@/api/api';
  import Vue from 'vue';
  import cmsMethods from '@/utils/cmsItems.js';
  import {
    mapState,
    mapMutations
  } from 'vuex';
  import {
    MERCHANT_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    SYSTEM_INFO,
    CART_KEY,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  // import matomo from 'wechat-matomo';
  import event from '@/utils/event.js';
  import sr from 'sr-sdk-wxapp'
  const pageTitles = {
    // 页面标题翻译
    'app/launch': 'app/launch',
    'pages/home/home': '首页',
    'pages/customer/customer': '我',
    'pages/item/category': '分类',
    'pages/cart/cart': '购物车',
    'pages/item/search': '商品列表',
    'pages/order/list': '订单列表',
    'pages/order/paySuccess': '支付成功',
    'pages/customer/registerSetting': '设置',
    'pages/item/item': '商品详情',
    'pages/order/submit': '确认订单',
    'pages/customer/address': '地址管理',
    'pages/order/details': '订单详情',
    'pages/order/logistics': '物流信息查询',
    'pages/return/return': '退货列表',
    'pages/return/details': '退货详情',
    'pages/order/reLogistics': '填写退货物流信息',
    'pages/return/applySuccess': '申请成功',
    'pages/util/redirect': '扫码跳转',
    'pages/store/store': '门店列表',
    "pages/exploration/exploration":"探索",
    'pages/item/categoryList': '商城PLP',
    'pages/item/categoryListTs': 'TSPLP',
    'pages/item/balloutTime': '抽签购PLP',
	  'pages/y200/y200': '200周年落地页',
		'pages/customer/newJoinMemberModal': '专属注册页面',
		'pages/customer/scanCode': '1v1页面'
		

  };
  const pagePath = {
    /*** MAIN  */
    '/pages/home/home': '/pages/home/home',
    '/pages/shopCart/shopCart': '/pages/cart/cart',
    '/pages/cart/cart': '/pages/cart/cart',
    '/pages/cms/items': '/pages/cms/items',
    '/pages/cms/page': '/pages/cms/page',
    '/pages/homeVideo/homeVideo': '/pages/homeVideo/homeVideo',
    /*** CUSTOMER  */
    '/pages/info/info': '/pages/info/info',
    '/pages/customer/customer': '/pages/info/info',
    '/pages/customer/couponList': '/pages/customer/couponList',
    '/pages/customer/favorites': '/pages/customer/favorites',
    '/pages/customer/joinSuccess': '/pages/customer/joinSuccess',
    '/pages/customer/settings': '/pages/customer/settings',
    '/pages/customer/memberGrowth': '/pages/customer/memberGrowth',
    '/pages/customer/address': '/pages/customer/address',
    '/pages/customer/registerSetting': '/pages/customer/registerSetting',

    /*** INVOICE  */
    '/pages/invoice/apply': 'pages/invoice/apply',
    '/pages/invoice/details': '/pages/invoice/details',
    '/pages/invoice/list': '/pages/invoice/list',
    '/pages/invoice/save': '/pages/invoice/save',
    /*** ITEM  */
    '/pages/search/search': 'pages/item/categoryNew',
    '/pages/category/category': 'pages/item/categoryNew',
    '/pages/item/item': '/pages/item/item',
    '/pages/item/sizeGuide': '/pages/item/sizeGuide',
    '/pages/item/category': 'pages/item/categoryNew',
    '/pages/item/categoryNew': 'pages/item/categoryNew',
    /*** ORDER  */
    '/pages/order/details': '/pages/order/details',
    '/pages/order/list': '/pages/order/list',
    '/pages/order/logistics': '/pages/order/logistics',
    '/pages/order/reLogistics': '/pages/order/reLogistics',
    '/pages/order/submit': '/pages/order/submit',
    '/pages/order/paySuccess': '/pages/order/paySuccess',
    /*** RETURN  */
    '/pages/return/return': '/pages/return/return',
    '/pages/return/applySuccess': '/pages/return/applySuccess',
    '/pages/return/details': '/pages/return/details',
    /*** UTIL  */
    '/pages/util/error': '/pages/util/error',
    '/pages/util/help': '/pages/util/help',
    '/pages/util/redirect': '/pages/util/redirect',
    /**收藏**/
    '/pages/favorites/favorites': '/pages/customer/favorites',
    // 盈钻
    '/pages/litha/litha': '/pages/litha/litha',
		//
		'/mp-revamp/toH5Page/toH5Page':'/mp-revamp/toH5Page/toH5Page',
		'/mp-revampstore-list/storeList':'/mp-revampstore-list/storeList',
		"/pages/exploration/exploration":"/pages/exploration/exploration",
		'/pages/item/categoryListTs': '/pages/item/categoryListTs',
     //抽签购PLP
		'/pages/item/balloutTime': '/pages/item/balloutTime',
    
      // 200周年落地页
    'pages/y200/y200': 'pages/y200/y200',
      // 专属注册页面
    "pages/customer/newJoinMemberModal": "pages/customer/newJoinMemberModal",
      // 1v1页面
     "pages/customer/scanCode": "pages/customer/scanCode",
  };

  let enableMatomo = uni.getStorageSync('enableMatomo') || true;
  let reportUrl = uni.getStorageSync('reportUrl') || 'https://analysis.cloud.efashionchina.com/matomo.php';
  let siteId = uni.getStorageSync('siteId') || 18;
  const wxCloudEnvJson = {
    formal: 'efashioncloud-prod-6dcw1c6b0134a',
    trial: 'efashioncloud-test-0d70ca69a0044'
  }
  export default {
    config: {
      window: {
        backgroundTextStyle: 'dark',
        navigationBarBackgroundColor: '#FFFFFF',
        navigationBarTitleText: uni.getStorageSync('storeName') || 'SANZEN-IN官网',
        navigationBarTextStyle: 'black',
        enablePullDownRefresh: false,
        backgroundColor: '#EFEFEF',
        navigationStyle: 'default',
        onReachBottomDistance: 300
      }
    },

    globalData: {
      // matomo: matomo.initTracker(reportUrl, siteId, {
      //   pageTitles
      // }),
      isLogin: false,
      isIpx: false,
      isSystem: 'Android',
      flag: false,
      share: false,
      title: pageTitles,
      siteId: null,
      reportUrl: null,
      pagePath: pagePath,
      brandType: -1,
      initTrack: 0,
      pageUrl: null,
      smsTemplateId: '1019',
      smsPlatform: 'aliyun',
      merchantInfo: {},
      customerInfo: null,
      onLineServiceX: 0,
      onLineServiceY: 0,
      onLineServiceIithaX: 0,
      onLineServiceIithaY: 0,
      whMovablearea: 0,
      moveAnimation: false,
      userLogin: false,
      memberDetails: {},
      userSpecicalInfo: {},
      isAuthUserInfo: {},
      cartNum: 0,
      openId: '',
      unionId: '',
      isAuthUser: false,
      autoBook: false,
      showCheckoutRemark: '', //结算页是显示备注开关
      cancelTime: '',
      refreshFavoritesList: false,
      favoritePageScrollTop: 0,
      favoriteListLength: 0,
      navBarHeight: 0,
      abable: true, //是否开启abtes。TODO 保留字段，待实现服务端（或推送提醒由客户端选择）配置
      abGetDone: false, //是否完成了abtest数据的请求
      abConfig: {}, //获取的abtest配置数据，包含一个ab测试下的一个场景（版本）数据
      cmsPreview: false, // cms 预览
      cl_tracker: null,
      pathOptions: null, //神策埋点传递公共属性给ar页面
      event,
      $sr: sr,
      api,
      shareImage: "", //  小程序全局配置的分享图片
      shareTitle: "", //  小程序全局配置的分享标题
      speciallyInviteShowLists:[],  //  已展示的特邀活动弹窗
      balloutBannerStatus: false,   //  抽签购横幅是否展示
      plpballoutBannerShowList:[], // plp页面横幅
			isFromApp: false,	//	是否从其他app跳入小程序
    },

    constructor() {
      //super();
      this.use('requestfix');
      this.use('promisify');
    },

    onLaunch: async function(options) {
			let that = this;
			try{
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					msg: "onLaunch执行",
					options: JSON.stringify(options)
				})
				this.handleSetSrSetuser();
				if (api.environment == "formal") {
					wx.cloud.init({
						// env 云开发调用会请求到哪个云开发环境的资源
						env: wxCloudEnvJson[api.environment]
					})
				}
				
				const version = wx.getSystemInfoSync().SDKVersion
				let versionIsOk = that.$commonFunction.compareVersion(version, '2.19.0')
				if (versionIsOk == 1) {
					wx.getChannelsLiveInfo({
						finderUserName: "sphvxkhvg8bIlSK",
						success: (res) => {
							uni.setStorageSync("channelsLiveInfo", res)
						},
						complete: (res) => {}
					})
					wx.getChannelsLiveNoticeInfo({
						finderUserName: "sphvxkhvg8bIlSK",
						success: (res) => {
							if (res.errMsg == "getChannelsLiveNoticeInfo:ok") {
								uni.setStorageSync("channelsLiveNoticeInfo", res)
							}
						},
						complete: (res) => {}
					})
				} else {
					// console.log('当前微信版本过低，暂无法使用视频号直播相关功能。')
					// wx.showModal({
					//   title: '提示',
					//   content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
					// })
				}

				
				that.globalData.pathOptions = options?.query || null;
				that.$commonSensors.commonUtmRegister('utm', options);
				that.cl_tracker = cl_tracker.cl_tracker;
				that.cl_tracker.track('mini_program_open', 'THE MACALLAN EBOUTIQUE麦卡伦', 'wx158a61365a8c8fd6', {
					targetName: 'THE MACALLAN EBOUTIQUE麦卡伦',
					targetId: 'wx158a61365a8c8fd6',
					source: options.query.cl_sr,
					contentName: options.query.cl_ctnm,
					source1: options.query.cl_source1,
					campaign: options.query.cl_cp,
				});

				if (uni.getUserProfile) {
					uni.setStorageSync('canIUseGetUserProfile', true);
				} else {
					uni.setStorageSync('canIUseGetUserProfile', false);
				}
				//检测版本更新
				const updateManager = wx.getUpdateManager();
				if (!!updateManager) {
					updateManager.onCheckForUpdate(function(res) {
						if (res.hasUpdate) {}
					});
					updateManager.onUpdateReady(function() {
						updateManager.applyUpdate();
					});
				}

				//EFSTracking InitTracker
				try {
					this.$EFSTracking.initTracker({
						scene: options.scene,
						vue: Vue,
						version: '1.0'
					});
					if (this.globalData.abable) {
						this.$EFSABTestTracking.init({
							scene: options.scene,
							vue: Vue,
							version: '1.0'
						});
					}
				} catch (err) {}

				let query = options.query;
				if (options.sourcecode != undefined && options.sourcecode != null && options.sourcecode != '') {
					uni.setStorageSync('sourceCode', options.sourcecode);
				}
				// 通过分享卡片进入 获取shareMemberCode
				uni.setStorageSync('firstEnter', true)
				this.$store.commit('changeIsForeignMobile', true);
				if (options.query) {
					let shareMemberCode = options.query.shareMemberCode || '';
					let sceneCode = options.query.sceneCode || '';
					let sceneType = options.query.type || '';
					uni.setStorageSync('sceneType', sceneType)

					if (shareMemberCode) {
						uni.setStorageSync('sceneCode', sceneCode)
						uni.setStorageSync('shareMemberCode', shareMemberCode)

					} else {
						uni.removeStorageSync('shareMemberCode')
						uni.removeStorageSync('sceneCode')
					}
					if (sceneType == 'taskHelp') {
						let taskParams = JSON.parse(decodeURIComponent(options.query.params))
						uni.setStorageSync('taskParams', taskParams)
					} else {
						uni.removeStorageSync('taskParams')
					}

				}
				//	是否爱奇艺渠道进入小程序
				if (options.scene === 1069 && (options?.query?.utm_source == "Iqiyi" || options?.query?.utm_source == "iqiyi")) {
					this.globalData.isFromApp = true;
				}
				if (options.scene === 1007 || options.scene === 1008) {
					that.globalData.share = true;
				} else {
					that.globalData.share = false;
				}
				let systemInfo = uni.getSystemInfoSync();

				uni.setStorageSync(SYSTEM_INFO, systemInfo);
				let yHeight = 50;
				let yArea = 70;
				let screenHeight = systemInfo.screenHeight;
				if (screenHeight <= 568) {
					yHeight = 145;
				} else if (screenHeight <= 667) {
					yHeight = 160;
				} else if (screenHeight <= 736) {
					yHeight = 170;
				} else if (screenHeight <= 812) {
					yHeight = 195;
					yArea = 100;
				} else if (screenHeight <= 896) {
					yHeight = 210;
					yArea = 110;
				} else {
					yHeight = 240;
					yArea = 120;
				}
				that.globalData.onLineServiceX = uni.getSystemInfoSync().windowWidth - 72 + 'px';
				that.globalData.onLineServiceY = screenHeight - yHeight - 60 + 'px';
				that.globalData.onLineServiceIithaX = uni.getSystemInfoSync().windowWidth - 48 + 'px';
				that.globalData.onLineServiceIithaY = screenHeight - yHeight - 130 + 'px';
				that.globalData.whMovablearea = screenHeight - yArea + 'px';
				let isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
					systemInfo.model.indexOf('unknown<iPhone13') !== -1 || systemInfo.model.indexOf('iPhone 12/13') !== -1 ||
					systemInfo.model.indexOf('iPhone 14') !== -1 || systemInfo.model.indexOf('iPhone 15') !== -1;
				that.globalData.isIpx = isIpx;
				let isSystem = systemInfo.system.indexOf('Android') !== -1;
				that.globalData.isSystem = isSystem;
				that.$store.commit('changeIsIpx', isIpx);
				// 自定义navBar高度
				let statusBarHeight = systemInfo.statusBarHeight;
				let rect = uni.getMenuButtonBoundingClientRect ? uni.getMenuButtonBoundingClientRect() : null; //胶囊按钮位置信息
				uni.getMenuButtonBoundingClientRect();
				let titleBarHeight = (function() {
					//导航栏高度
					let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
					return 2 * gap + rect.height;
				})();
				//	微信登录
				await that.handleWxLogin(3);
				//  小程序全局分享配置查询
				that.getMiniAppShareConfig();

				that.globalData.navBarHeight = statusBarHeight + titleBarHeight;
				const accountInfo = uni.getAccountInfoSync(); // 小程序appId

				// 获取商户信息
				let merchantInfo = await api.merchantInfo(accountInfo.miniProgram.appId);
				if (merchantInfo.code === 200) {
					let merchantData = merchantInfo.data;
					let brandType = merchantData.cloudMerchantId == 100000041 ? 0 : merchantData.cloudMerchantId == 100000054 ?
						1 : merchantData.cloudMerchantId == 100000057 ? 2 : -1;
					this.globalData.brandType = brandType;
					that.$store.commit('changeBrandType', brandType);
					that.globalData.app_id = accountInfo.miniProgram.appId;
					that.globalData.flag = true;
					that.globalData.merchantInfo = merchantData;
					// that.$isResolve();
					// 存储商户信息
					uni.setStorageSync(MERCHANT_INFO, merchantData);

					//try to get abtest config for current client user
					try {
						if (this.globalData.abable) {
							this.$EFSABTestTracking.getExperimentABTesting('');
						}
					} catch (err) {
						// console.error('ABTest config init fail:' + err);
					}
					if (this.$programSetting.customTabbar) {
						uni.hideTabBar()
					}
					that.$commonFunction.commonLoginNew().then((res) => {
						that.$commonSensors.commonSetProfile('customer', res.data)
						that.$sr.setUser({
							open_id: res.data.openId,
							union_id: res.data.unionId
						})
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							is_member: "true",
							custom_id: res.data.customerId ? String(res.data.customerId): "",
							msg: "onLaunch-commonLoginNew-then-神策注册会员属性register"
						})
						//	会员信息获取
						that.$commonFunction.getMemberDetailNew().then((res) => {
							that.$commonSensors.commonSetProfile('member', res.data);
							// 莫凡日志
							const _isNewMember = res.data.isNewMember ? "true" : "false";
							commonMorefunLogs.aliYunMorefunLogs({
								is_member: "true",
								is_new_member: _isNewMember,
								msg: "onLaunch-getMemberDetailNew-then-神策注册会员属性register"
							})
						}).catch((err) => {
							commonMorefunLogs.aliYunMorefunLogs({
								msg: "onLaunch-getMemberDetailNew-error",
								err: JSON.stringify(err)
							})
						});
						that.$commonFunction.getStoreConfigOnly().then(() => {
							that.$isResolve();
						}).catch(() => {
							that.$isResolve();
						})

						that.cl_tracker.push({
							identityType: 'applet-wechat',
							identityValue: res.data.openId, // identityValue 是用户的open_id
							identityType2: 'wechat-unionid',
							identityValue2: res.data.unionId
						});
						that.$commonFunction.checkCartNew().then((res) => {
							that.$commonFunction.getCartList().then((res) => {
								that.$commonFunction.setInitTaskCenter().then(() => {}).catch(() => {})
							}).catch((err) => { });
						}).catch((err) => { });
					}).catch((err) => {
						that.$sensors.register({
							is_member: false,
							is_new_member: false,
						});
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							is_member: "false",
							is_new_member: "false",
							err: JSON.stringify(err),
							msg: "onLaunch-commonLoginNew-catch-神策注册会员属性register",
							msg2: "清除缓存数据"
						})
						let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
						that.$commonSensors.commonSetProfile('customer', false)
						if (err.code == -1001 && !!customerInfo) {
							wx.removeStorageSync('customerInfo')
							wx.removeStorageSync('memberDetails')
							wx.removeStorageSync('cartKey')
							wx.removeStorageSync('isAgreePolicy')
							wx.removeStorageSync('buyerPartPayment')
						}
						that.$store.commit('changeAgeModalCheckedState', false);
						that.$store.commit('changeSkdModalCheckedState', false);
						that.$commonFunction.getStoreConfigOnly().then(() => {
							that.$isResolve();
						}).catch(() => {
							that.$isResolve();
						})
					});
				}
				// 获取记录搜索词的uid标识
				let userUid = uni.setStorageSync('searchUid') || '';
				if (!userUid) {
					this.getbasicAutoNumber();
				}

				this.$EFSTracking.trackingPage('onLaunch', {
					route: __wxRoute
				});
			}catch(e){
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					msg: "onLaunch执行-error",
					err: JSON.stringify(e)
				})
			}
    },
    onShow: async function(options) {
			try{
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					msg: "onShow执行"
				})
				this.handleSetSrSetuser();
				await this.$onLaunched;
				let that = this;
				this.cl_tracker.track('mini_program_view', 'THE MACALLAN EBOUTIQUE麦卡伦', 'wx158a61365a8c8fd6', {
					targetName: 'THE MACALLAN EBOUTIQUE麦卡伦',
					targetId: 'wx158a61365a8c8fd6'
				});
				uni.setStorageSync('sceneCode', options.scene)
				if (uni.getUserProfile) {
					uni.setStorageSync('canIUseGetUserProfile', true);
				} else {
					uni.setStorageSync('canIUseGetUserProfile', false);
				}
				if (!!options.query.tagShareCode && (options.scene === 1007 || options.scene === 1008)) {
					// 统计分享
					uni.setStorageSync('tagShareCode', options.query.tagShareCode)
					that.statShare(options.query.tagShareCode)
				}
				//注册参数
				if (options?.query?.storeId || options?.query?.staffId || options?.query?.staffName || options?.query?.storeName) {
					let values = {}
					const {
						storeId,
						staffId,
						staffName,
						storeName
					} = options.query
					values.c_clienteling_store_id = storeId
					values.c_clienteling_staff_id = staffId
					values.c_clienteling_staff_name = staffName
					values.c_clienteling_store_name = storeName
					that.setExpiringStorage('registerParams', values, 300)
					//172800
				}
			}catch(e){
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					msg: "onShow执行-error",
					err: JSON.stringify(e)
				})
			}
    },
    onError(error) {},
    onHide() {
      uni.removeStorageSync('showBlocka');
      uni.setStorageSync('firstEnter', true)
    },

    methods: {
			//	调用微信登录方法  获取用户openId和unionId
			async handleWxLogin(index){
				const that = this;
				return new Promise((resolve, reject)=>{
					that.$commonFunction.commonUniLogin().then((commonUniLoginRes) => {
						that.$commonSensors.binduserid(commonUniLoginRes.data.openid, commonUniLoginRes.data.unionId)
						that.$sr.setUser({
							open_id: commonUniLoginRes.data.openid,
							union_id: commonUniLoginRes.data.unionId
						})
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							msg: "handleWxLogin-神策绑定用户openid和unionId-binduserid",
							msg2: "handleWxLogin-有数setUser",
							index: String(index)
						})
						resolve(commonUniLoginRes)
					}).catch((err) => {
						that.$commonSensors.commonSetProfile('customer', false)
						// that.$isResolve();
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							msg: "handleWxLogin-error-神策绑定用户openid和unionId-binduserid",
							msg2: "handleWxLogin-error-有数setUser",
							err: JSON.stringify(err),
							index: String(index)
						})
						if(index > 0){
							// 获取openid接口报错，重复调用3次
							let _num = index-1;
							that.handleWxLogin(_num);
						}
						resolve(null)
					});
				});
			},
			//	腾讯有数埋点设置openid
			async handleSetSrSetuser(){
				try{
					const res = uni.getStorageSync("uniLoginInfo");
					if(res && res.openid && res.unionId){
						this.$sr.setUser({
							open_id: res.openid,
							union_id: res.unionId
						})
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							msg: "handleSetSrSetuser-有数埋setUser"
						})
					}else{
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							msg: "handleSetSrSetuser-有数埋点未获取到openid",
							res: JSON.stringify(res)
						})
					}

					//	神策埋点 用户会员信息绑定
					const memberData = uni.getStorageSync("memberDetails");
					if(memberData && memberData.id){
						//	神策埋点 会员判断
						this.$sensors.register({
						  is_member: true,
						});
						this.$commonSensors.commonSetProfile('member', memberData)
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							member_id: String(memberData.id),
							is_member: "true",
							msg: "handleSetSrSetuser-神策注册会员属性register"
						})
					}else{
						this.$sensors.register({
						  is_member: false,
						});
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							member_id: memberData.id || "",
							is_member: "false",
							msg: "handleSetSrSetuser-神策注册会员属性register"
						})
					}
					//	神策埋点 用户信息绑定
					const customerData = uni.getStorageSync("customerInfo");
					if(customerData && customerData.openId){
						this.$commonSensors.binduserid(customerData.openid, customerData.unionId)
						this.$sensors.setProfile({
						  custom_id: customerData.customerId || "",
						  is_member: memberData && memberData.id ? true : false,
						});
						if (!!customerData.customerId) {
						  this.$sensors.bind("identity_eb_customer_id", customerData.customerId);
						}
						let _mobile = "";
						if (!!customerData.mobile) {
						  this.$sensors.bind("$identity_mobile", customerData.mobile);
							const _m2 = String(customerData.mobile);
							_mobile = _m2.replace(_m2.substring(3,7), '****');
						}
						// 莫凡日志
						commonMorefunLogs.aliYunMorefunLogs({
							usermobile: _mobile,
							identity_eb_customer_id: customerData.customerId ? String(customerData.customerId) : "",
							is_member: memberData && memberData.id ? "true" : "false",
							msg: "handleSetSrSetuser-神策注册会员属性setProfile"
						})
					}
				}catch(e){
					// 莫凡日志
					commonMorefunLogs.aliYunMorefunLogs({
						msg: "handleSetSrSetuser-error",
						err: JSON.stringify(e)
					})
				}
			},
      //  小程序分享配置
      async getMiniAppShareConfig(){
        const shareRes = await api.getShareinfoByCode({
          code: 'miniappShareConfig'
        });
        if (shareRes && shareRes.success && shareRes.data && shareRes.data.value) {
          const res = JSON.parse(shareRes.data.value);
          this.globalData.shareImage = res.imageUrl || "";
          this.globalData.shareTitle = res.title || uni.getStorageSync('storeName') || 'THE MACALLAN EBOUTIQUE麦卡伦';
        }
      },
	   setExpiringStorage(key, value, expireSeconds) {
         const now = new Date().getTime();
         const expireTime = now + expireSeconds * 1000;
         uni.setStorage({
           key: key,
           data: {
             value: value,
             expireTime: expireTime
           },
           success: function() {
           }
         });
       },
      reNewGiftBoxTrack(eventName) {
        let {
          tsActId,
          name
        } = uni.getStorageSync('TsInfo');
        let trackParams = {
          "c_product_name": "麦卡伦 THE MACALLAN 臻味啡凡 单一麦芽威士忌",
          "c_product_brand": "麦卡伦macallan",
          "c_product_price": "1500",
          // "c_product_year":"",
          "c_product_series": "臻味不凡系列·臻味啡凡",
          // "c_product_scenarios":"",
          // "c_product_taste":"",
          "c_product_alcoholconcentration": "44%",
          "c_product_volume": "700ml",
          // "c_product_id":"",
          "c_popup_type": "商品",
          "c_campaignID": tsActId,
          "c_campaignName": name,
        }
        this.commonClTrack(eventName, trackParams);
      },
      async getTaskInfo() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        const res = await api.getTaskInfo({
          method: 'GET',
          header: {
            jwt: customerInfo.jwt
          },
        })
        if (res.code === 1000) {
          return res.data
        }
      },
      async finishTask(taskCenterCode, taskContentId, taskContentName, isInviteFriends) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let {
          unionId
        } = uni.getStorageSync(USER_SPECICAL_INFO);
        let memberDetails = uni.getStorageSync('memberDetails');
        const res = await api.finishTask({
          method: 'PUT',
          header: {
            jwt: customerInfo.jwt
          },
          query: {
            isInviteFriends: isInviteFriends,
            memberId: memberDetails.memberId,
            memberLevelId: memberDetails.memberLevelId,
            memberLevelName: memberDetails.memberLevel.levelName,
            merchantId: memberDetails.merchantId,
            mobile: customerInfo.mobile,
            remark: `完成${taskContentName}任务`,
            taskCenterCode: taskCenterCode,
            taskContentId: taskContentId,
            unionId: unionId
          }
        })
        if (res.code === 1000) {
          return true
        }
      },
      sdkSetting() {
        // 可以修改是否自动采集以下事件
        // mini_program_open 事件开关
        this.cl_tracker.setEnableAutoTrackMiniProgramOpen(true);
        // mini_program_view 事件开关
        this.cl_tracker.setEnableAutoTrackMiniProgramView(true);
        // mini_program_exit事件开关
        this.cl_tracker.setEnableAutoTrackMiniProgramExit(true);
        // mini_program_resign_active 事件开关
        this.cl_tracker.setEnableAutoTrackMiniProgramResign(true);
      },
      /** 获取商户配置信息
       * @auth: long
       * @param  {[string]} path [配置接口path]
       * @param  {[string]} storeKey [store存储中的key值]
       * @param  {[string]} localKey [本地storage中的key值]
       */
      getStoreConfig: async function(path, storeKey, localKey) {
        let that = this;
        const json = await api.getStoreInfo({
          method: 'GET',
          query: {
            config_client_id: 'efcloud',
            config_path: path,
            config_scope: 'Store',
            config_scope_id: that.globalData.merchantInfo.cloudMerchantStoreId || uni.getStorageSync(
              MERCHANT_INFO).cloudMerchantStoreId,
            merchant_id: that.globalData.merchantInfo.cloudMerchantId || uni.getStorageSync(MERCHANT_INFO)
              .cloudMerchantStoreId
          }
        });
        if (json.code === 1000) {
          if (path == 'store/system_config/store_version') {
            let oldVersion = uni.getStorageSync(localKey);
            if (oldVersion !== '' && json.data.value !== oldVersion) {
              uni.removeStorageSync('addressId');
              uni.removeStorageSync('signState');
              uni.removeStorageSync('cartKey');
              uni.removeStorageSync('customerInfo');
              uni.removeStorageSync('bindObj');
              uni.removeStorageSync('background');
              uni.removeStorageSync('userInfo');
              uni.removeStorageSync('uuid');
              uni.removeStorageSync('userSpecialInfo');
            }
            that.$store.commit(storeKey, json.data.value);
            uni.setStorageSync(localKey, json.data.value);
          } else if (path == 'store/store_design/global_image_scaling') {
            let proportion = json.data.value;
            let proportionArr = proportion.split(':');
            let result = proportionArr[0] / proportionArr[1];
            that.$store.commit(storeKey, result);
            uni.setStorageSync(localKey, result);
          } else {
            that.$store.commit(storeKey, json.data.value);
            uni.setStorageSync(localKey, json.data.value);
            if (path == 'tracking/matomo/enable' && json.data.value) {
              await that.getStoreConfig('tracking/matomo/report_url', 'changeReportUrl', 'reportUrl');
              await that.getStoreConfig('tracking/matomo/site_id', 'changeSiteId', 'siteId');
            } else if (path == 'tracking/matomo/report_url') {
              that.globalData.reportUrl = json.data.value;
            } else if (path == 'tracking/matomo/site_id') {
              that.globalData.siteId = json.data.value;
            } else if (path == 'service/sms/templateid') {
              that.globalData.smsTemplateId = json.data.value;
            } else if (path == 'service/sms/platform') {
              that.globalData.smsPlatform = json.data.value;
            } else if (path == 'order/checkout/show_checkout_remark') {
              that.globalData.showCheckoutRemark = json.data.value;
            } else if (path == 'service/subscribe_message/new_product_sale_remind') {
              let status = json.data.value;
              if (status) {
                await that.getStoreConfig('service/subscribe_message/on_sale_inform_in_advance_time',
                  'changeAdvanceTime', 'advanceTime');
                await that.getStoreConfig('service/subscribe_message/new_product_sale_template_id',
                  'changeSaleTemplate', 'saleTemplate');
              }
            } else if (path == 'order/common/audit_cancel_order') {
              that.globalData.cancelTime = json.data.value;
            }

            if (that.globalData.initTrack == 0 && that.globalData.siteId != null && that.globalData.reportUrl !=
              null) {
              // matomo.initTracker(that.globalData.reportUrl, that.globalData.siteId, {
              //   pageTitles
              // });
              // matomo.tracker.trackPageView(pageTitles['app/launch'], 'app/launch');
              // matomo.tracker.trackPageView(pageTitles[that.globalData.pageUrl], that.globalData.pageUrl);
              that.globalData.initTrack = 1;
            }
          }
        }
      },
      /** 获取商户配置信息
       * @auth: long
       * @param  {[string]} path [配置接口path]
       * @param  {[string]} storeKey [store存储中的key值]
       * @param  {[string]} localKey [本地storage中的key值]
       */
      getStoreConfigSimple: async function(path, localKey) {
        let that = this;
        const json = await api.getStoreInfo({
          method: 'GET',
          query: {
            config_client_id: 'efcloud',
            config_path: path,
            config_scope: 'Store',
            config_scope_id: that.globalData.merchantInfo.cloudMerchantStoreId || uni.getStorageSync(
              MERCHANT_INFO).cloudMerchantStoreId,
            merchant_id: that.globalData.merchantInfo.cloudMerchantId || uni.getStorageSync(MERCHANT_INFO)
              .cloudMerchantStoreId
          }
        });
        if (json.code === 1000) {
          uni.setStorageSync(localKey, json.data.value);
        }
      },
      /** 获取商户接口配置信息
       * @auth: long
       * @param  {[string]} path [配置接口path]
       * @param  {[string]} storeKey [store存储中的key值]
       * @param  {[string]} localKey [本地storage中的key值]
       * @param  {[string]} config_scope_id [config_scope_id]
       * @param  {[string]} merchant_id [商户id]
       */
      getStoreEnvironment: async function(path, config_scope_id, merchant_id) {
        let that = this;
        const json = await api.getEnvironment({
          method: 'GET',
          query: {
            config_client_id: 'efcloud',
            config_path: path,
            config_scope: 'Store',
            config_scope_id: config_scope_id,
            merchant_id: merchant_id
          }
        });
        if (json.code === 1000) {
          let baseUrl = 'https://api.cloud.efashionchina.com';
          if (json.data.value !== 'production') {
            baseUrl = 'https://api.' + json.data.value + '.cloud.efashionchina.com';
          }
          uni.setStorageSync('environment', baseUrl);
          // 获取商户配置信息
          // customize.getConfig();
          that.getStoreConfig('tracking/matomo/enable', 'changeEnableMatomo', 'enableMatomo');
          that.getStoreConfig('store/information/logo', 'changeStoreLogo', 'storeLogo');
          that.getStoreConfig('store/information/name', 'changeStoreName', 'storeName');
          if (this.$store.state.tabInfo == null || this.$store.state.tabInfo == []) {}
          // that.getStoreConfig('store/tabs/available_tabs', 'setTabInfo', 'tabInfo'); // 可删?
        }
      },

      /**
       * 获取唯一编码 做为用户的唯一标识uid。 需要永久保存在缓存中
       * dashboard统计搜索词
       */
      getbasicAutoNumber: async function() {
        let that = this;
        const number = await api.basicAutoNumber({
          method: 'GET'
        });
        if (number.code === 1000) {
          let uid_number = number.data.number;
          uni.setStorageSync('searchUid', uid_number);
        }
      },


      /** 公用分享
       * @auth: long
       * @param  {[string]} title [分享标题]
       * @param  {[string]} path [分享的页面路径]
       * @param  {[string]} imageUrl [分享图片]
       */
      async commonShare(res, title, path, imageUrl) {
        // 设置默认分享地址和默认标题，标题和分享图片非必传 path必传
        // let defaultImageUrl =
        // this.$sr.track('page_share_app_message', {
        //   "from_type": res.from,
        //   "share_title": title || 'THE MACALLAN EBOUTIQUE麦卡伦',
        //   "share_path": path,
        //   "share_image_url": imageUrl,
        //   "share_to": "friends",
        // })
        let shareCode = await this.recordShare(path)
        if (path.indexOf('?') == -1) {
          path = path + `?tagShareCode=${shareCode}`
        } else {
          path = path + `&tagShareCode=${shareCode}`
        }
        //   'https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/shareImage/2020011664953.jpg';
        let defaultTitle = uni.getStorageSync('storeName') || '';
        return {
          title: title || defaultTitle,
          path: path,
          imageUrl: imageUrl
        };
      },
      async recordShare(path) {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let memberDetails = uni.getStorageSync('memberDetails');
        let params = {
          path: path,
          userType: 1,
          sceneType: 'SA',
          campaign: 'deafult-share',
          unionId: uni.getStorageSync(USER_SPECICAL_INFO).unionId,
          storeId: this.globalData.merchantInfo.cloudMerchantStoreId || merchantInfo.cloudMerchantStoreId,
          merchantId: this.globalData.merchantInfo.cloudMerchantId || merchantInfo.cloudMerchantId,
        }
        let cutomerParams = {}
        if (!!memberDetails && !!customerInfo) {
          cutomerParams = {
            customerId: customerInfo.customerId,
            mobile: memberDetails.mobile || '',
            memberId: memberDetails.memberId || '',
            nickname: memberDetails.nickName || '',
            memberLevelId: memberDetails.memberLevelId || '',
            memberLevelName: memberDetails.memberLevel && memberDetails.memberLevel.levelName,
          }
        }
        let queryParams = Object.assign({}, params, cutomerParams)
        let shareCode = await api.recordShare({
          method: 'POST',
          query: queryParams
        });
        if (shareCode.code === 1000) {
          return shareCode.data
        }
      },
      // 统计分享
      async statShare(sceneCode) {
        await this.$onLaunched;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let memberDetails = uni.getStorageSync('memberDetails');
        let unionId = uni.getStorageSync(USER_SPECICAL_INFO).unionId
        if (!unionId) {
          let json = await uni.login();
          if (json[1].code) {
            const rlt = await api.obtainUserOpenid({
              query: {
                app_id: uni.getAccountInfoSync().miniProgram.appId,
                js_code: json[1].code
              }
            });
            if (rlt.code === 1000) {
              unionId = rlt.data.unionId
            }
          }
        }
        if (!merchantInfo) {
          await this.getMerchantInfoCommon().then((res) => {
            merchantInfo = res
          })
        }
        let params = {
          userType: 1,
          sceneCode: sceneCode,
          unionId: unionId,
          storeId: merchantInfo.cloudMerchantStoreId || '',
          merchantId: merchantInfo.cloudMerchantId || '100000063',
        }
        let cutomerParams = {}
        if (!!memberDetails && !!customerInfo) {
          cutomerParams = {
            customerId: customerInfo.customerId || '',
            mobile: customerInfo.mobile || memberDetails.mobile,
            memberId: memberDetails.memberId || '',
            nickname: customerInfo.nickName || memberDetails.nickName,
            memberLevelId: memberDetails.memberLevelId || '',
            memberLevelName: memberDetails.memberLevel.levelName || '',
            unionId: uni.getStorageSync(USER_SPECICAL_INFO).unionId || customerInfo.unionId,
          }
          queryParams = Object.assign({}, params, cutomerParams)
          this.statRequest(queryParams)
        }
        let queryParams = {}
        if (!customerInfo || !memberDetails) {
          this.$commonFunction.commonLoginNew().then((res) => {
            customerInfo = res.data
            this.$commonFunction.getMemberDetailNew().then((res) => {
              memberDetails = res.data
              cutomerParams = {
                customerId: customerInfo.customerId || '',
                mobile: customerInfo.mobile || memberDetails.mobile,
                memberId: memberDetails.memberId || '',
                nickname: customerInfo.nickName || memberDetails.nickName,
                memberLevelId: memberDetails.memberLevelId || '',
                memberLevelName: memberDetails.memberLevel.levelName || '',
                unionId: uni.getStorageSync(USER_SPECICAL_INFO).unionId || customerInfo.unionId,
              }
              queryParams = Object.assign({}, params, cutomerParams)
              this.statRequest(queryParams)
            }).catch((err) => {
              queryParams = Object.assign({}, params, cutomerParams)
              this.statRequest(queryParams)
            });
          }).catch((err) => {
            queryParams = Object.assign({}, params, cutomerParams)
            this.statRequest(queryParams)
          });

        }

      },
      async statRequest(queryParams) {
        let rel = await api.statShare({
          method: 'POST',
          query: queryParams
        });
        if (rel.code === 1000) {}
      },

      /** 公用价格处理
       * @auth: long
       * @param  {[number]} value [需要处理的金额]
       * @param  {[number]} num [非整数保留的小数位]
       * @param  {[string]} imageUrl [分享图片]
       */
      moneyFormat(value, num) {
        num = num > 0 && num <= 20 ? num : 2;
        value = parseFloat((value + '').replace(/[^\d\.-]/g, '')).toFixed(num) + ''; //将金额转成比如 123.45的字符串
        var valueArr = value
          .split('.')[0]
          .split('')
          .reverse(); //将字符串的数变成数组
        const valueFloat = value.split('.')[1]; // 取到 小数点后的值
        let valueString = '';
        for (let i = 0; i < valueArr.length; i++) {
          valueString += valueArr[i] + ((i + 1) % 3 == 0 && i + 1 != valueArr.length ? ',' : ''); //循环 取数值并在每三位加个','
        }
        let money =
          valueString
          .split('')
          .reverse()
          .join('') +
          '.' +
          valueFloat; //拼接上小数位
        if (money.indexOf('.00') !== -1) {
          money = money.substring(0, money.length - 3);
        }
        return money;
      },

      checkBlackList: async function() {
        // let that = this;
        // let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || that.globalData.customerInfo;
        // let json = await api.checkBlackList({
        //   method: 'GET',
        //   header: {
        //     jwt: customerInfo.jwt
        //   }
        // });
        // if (json.code !== 1000) {
        //   uni.setStorageSync('isBlackListUser', true)
        //   that.getCartList()
        // } else {
        //   uni.setStorageSync('isBlackListUser', false)
        //   that.getCartList()
        // }
        // return json.code !== 1000
      },
      /** 判断用户购物车状态
       * @auth: long
       * @time: 2021-02-08
       */
      checkCart: async function(customerInfo) {
        let that = this;
        let cart_key = '';
        let merchantInfo = that.globalData.merchantInfo;
        if (customerInfo) {
          let res = await api.checkCart({
            method: 'POST',
            header: {
              jwt: customerInfo.jwt
            },
            query: {
              customerId: customerInfo.customerId,
              merchantId: merchantInfo.cloudMerchantId,
              orderSource: 'wxapp',
              storeId: merchantInfo.cloudMerchantStoreId
            }
          });
          if (res.code === 1000) {
            cart_key = res.data;
            uni.setStorageSync('cartKey', cart_key);
            that.globalData.cartKey = cart_key;
          } else {
            let cartRes = await api.initCart({
              method: 'POST',
              header: {
                jwt: customerInfo.jwt
              },
              query: {
                customerId: customerInfo.customerId,
                merchantId: merchantInfo.cloudMerchantId,
                orderSource: 'wxapp',
                storeId: merchantInfo.cloudMerchantStoreId
              }
            });
            cart_key = cartRes.data.cartKey;
            uni.setStorageSync('cartKey', cart_key);
            that.globalData.cartKey = cart_key;
          }
          // that.getCartList();
        }
      },

      reapplyJWT: async function() {
        let that = this;
        let tokenCustomer = uni.getStorageSync(CUSTOMER_INFO);
        let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
        let openId = userSpecialInfo.openid;
        let res = await uni.login();
        const accountInfo = uni.getAccountInfoSync()
        if (res.code) {
          let systemInfo = uni.getSystemInfoSync();
          uni.setStorageSync(SYSTEM_INFO, systemInfo);
          const rlt = await api.obtainUserOpenid({
            query: {
              app_id: accountInfo.miniProgram.appId,
              js_code: res.code
            }
          });
          if (rlt.code === 1000) {
            if (rlt.data.openid) {
              uni.setStorageSync(USER_SPECICAL_INFO, rlt.data);
              //获取商户信息
              let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
              if (merchantInfo.cloudMerchantId) {
                let customerInfo = await api.checkUser({
                  method: 'POST',
                  query: {
                    appId: accountInfo.miniProgram.appId,
                    merchantId: that.globalData.merchantInfo.cloudMerchantId || uni.getStorageSync(MERCHANT_INFO)
                      .cloudMerchantId,
                    openId: rlt.data.openid,
                    loginToken: rlt.data.loginToken || ''
                  }
                });
                if (customerInfo.code == 1000) {
                  that.globalData.userLogin = true;
                  that.globalData.customerInfo = customerInfo.data;
                  uni.setStorageSync(CUSTOMER_INFO, customerInfo.data);
                } else {
                  that.globalData.userLogin = false;
                }
              }
            }
          }
        }
      },
      /**
       * 获取用户会员信息
       * @param jwt
       * @return {Promise<void>}
       */
      getMemberDetail: async function(jwt) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || that.globalData.customerInfo;
        const memberDetailsResult = await api.getMemberDetails({
          header: {
            jwt: customerInfo.jwt || jwt
          }
        });
        if (memberDetailsResult.code == 1000) {
          const phoneNumberReg = /^1\d{10}$/;
          if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
            // 非大陆手机号按照非会员对待,重新入会
            uni.removeStorageSync('memberDetails');
            return null;
          }
          that.globalData.memberDetails = memberDetailsResult.data;
          uni.setStorageSync('memberDetails', memberDetailsResult.data);
        }
        return memberDetailsResult.data
      },
      //获取购物车商品列表
      getCartList: async function() {
        let that = this;
        that.$commonFunction.getCartList().then((res) => {

        }).catch((err) => {

        });
      },
      unique(arr) {
        for (var i = 0; i < arr.length; i++) {
          for (var j = i + 1; j < arr.length; j++) {
            if (arr[i].frontCode == arr[j].frontCode) {
              //第一个等同于第二个，splice方法删除第二个
              arr.splice(j, 1);
              j--;
            }
          }
        }
        return arr;
      },
      priceRulesDeal: async function(data) {
        let that = this;
        let customerInfo = uni.getStorageSync('customerInfo');
        let memberDetails = uni.getStorageSync('memberDetails') || that.globalData.memberDetails;
        let cgid = customerInfo.groupId;
        let clid = memberDetails.memberLevelId;
        let isActive = memberDetails.isActive == 'Active';
        let priceRulesJson = [];
        let priceRulesJson1 = [];
        let priceRulesJson2 = [];
        let json = {
          price: 0,
          rulesPrice: 0,
          hasRule: false,
          rulesArr: []
        };
        let yrJson = [];
        data.forEach(function(item, index, array) {
          if (item.showPreTag == 1) {
            let now = new Date().getTime() / 1000;
            let start = new Date(item.preStrategyStartTime.replace(/-/g, '/')).getTime() / 1000;
            let end = new Date(item.preStrategyEndTime.replace(/-/g, '/')).getTime() / 1000;
            if (now - start >= 0 && end - now > 0) {
              // yrJson.push(item)
              yrJson.push({
                groupIds: item.groupIds,
                groupVisible: item.groupVisible,
                memberLevels: item.memberLevels,
                // prePriceTag: item.prePriceTag,
                // preStrategyEndTime: item.prePriceTag,
                // preStrategyStartTime: item.prePriceTag,
                priceTag: item.prePriceTag,
                showPreTag: item.showPreTag,
                strategyEndTime: item.preStrategyEndTime,
                strategyId: item.strategyId,
                strategyPrice: item.strategyPrice,
                strategyStartTime: item.preStrategyStartTime
              });
            }
          }
        });
        data.forEach(function(item, index, array) {
          let now = new Date().getTime() / 1000;
          let start = new Date(item.strategyStartTime.replace(/-/g, '/')).getTime() / 1000;
          let end = new Date(item.strategyEndTime.replace(/-/g, '/')).getTime() / 1000;
          if (now - start >= 0 && end - now > 0) {
            priceRulesJson.push(item);
          }
        });
        priceRulesJson.forEach(function(item, index, array) {
          if (!item.groupIds && !item.memberLevels) {
            if (json.price == 0 && json.rulesPrice == 0) {
              json.price = item.strategyPrice;
              json.rulesPrice = item.strategyPrice;
              json.hasRule = true;
            }
          } else {
            if (item.groupVisible == 1) {
              priceRulesJson1.push(item);
            } else {
              let checkGroup = !item.groupIds || (!!item.groupIds && item.groupIds.indexOf(cgid) !== -1);
              let checkMemberLevel = !item.memberLevels || (!!item.memberLevels && isActive && item.memberLevels
                .indexOf(clid) !== -1);
              if (checkGroup && checkMemberLevel) {
                priceRulesJson1.push(item);
              } else {
                priceRulesJson2.push(item);
              }
            }
          }
        });
        priceRulesJson2.forEach(function(item, index, array) {
          for (var i = 1; i < priceRulesJson2.length; i++) {
            let levelSplice = JSON.stringify(item.memberLevels) == JSON.stringify(priceRulesJson2[i]
              .memberLevels);
            let groupSplice = JSON.stringify(item.groupIds) == JSON.stringify(priceRulesJson2[i].groupIds);
            if (index !== i && levelSplice && groupSplice) {
              priceRulesJson2.splice(i, 1);
            }
          }
        });
        if (priceRulesJson1.length > 0) {
          if (priceRulesJson2.length > 0) {
            if (priceRulesJson2[0].strategyId > priceRulesJson1[0].strategyId) {
              priceRulesJson2.push(priceRulesJson1[0]);
            } else {
              priceRulesJson2.unshift(priceRulesJson1[0]);
            }
          } else {
            priceRulesJson2.push(priceRulesJson1[0]);
          }
        }
        json.rulesArr = priceRulesJson2.concat(yrJson);
        return json;
      },
      isEnableEvaluate: async function() {
        let that = this;
        let customerInfo = that.globalData.customerInfo;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || '';
        if (!customerInfo || !customerInfo.jwt) {
          that.$commonFunction.commonLoginNew().then((res) => {}).catch((err) => {

          });
        } else {
          const shopCartList = await api.isEnableEvaluate({
            header: {
              jwt: customerInfo.jwt
            },
            query: {
              store_id: merchantInfo.cloudMerchantStoreId
            }
          });
          if (shopCartList.code === 1000) {
            uni.setStorageSync('isEnableEvaluate', options.sourcecode);
          }
        }
      },
      /** 获取商品评价信息
       * @auth: long
       * @param  {[Boolean]} goodsId [商品id]
       * @param  {[Boolean]} isSelection [是否精选]
       * @param  {[Boolean]} isReview, [是否有评价图片]
       * @param  {[Boolean]} isPdp [是否PDP页面]
       * @return {Promise<void>}
       */
      getPdpEvaluate: async function(goodsId, isSelection, isReview, isPdp, pi) {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
        const pdpEvaluateInfo = await api.pdpEvaluate({
          query: {
            isReviewImages: isReview,
            isSelection: isSelection,
            isPdp: isPdp,
            itemId: goodsId,
            pageNo: pi || 1,
            pageSize: 10,
            merchantId: merchantInfo.cloudMerchantId,
            storeId: merchantInfo.cloudMerchantStoreId
          }
        });

        return pdpEvaluateInfo;
      },
      /**
       * [isDuringDate 比较当前时间是否在指定日期范围内]
       * @author long
       * @DateTime 2022-01-14
       * @version  1.0
       * @param    date   [beginDateStr] [开始日期]
       * @param    date   [endDateStr]   [结束日期]
       * @return   Boolean
       */
      isDuringDate: function(beginDateStr, endDateStr) {
        let beginDate = beginDateStr;
        let endDate = endDateStr;
        let systemInfo = uni.getStorageSync(SYSTEM_INFO);
        let isIos = systemInfo.system.indexOf('iOS');
        if (isIos == 0) {
          beginDate = beginDate && new Date(beginDate.replace(/-/g, '/')).getTime();
          endDate = endDate && new Date(endDate.replace(/-/g, '/')).getTime();
        } else {
          beginDate = beginDate && new Date(beginDate).getTime();
          endDate = endDate && new Date(endDate).getTime();
        }
        var curDate = new Date();
        if (curDate >= beginDate && curDate <= endDate) {
          return true;
        }
        return false;
      },
      getCMSImageUrl: async function(identifier) {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        let mt = '1.0';
        if (!merchantInfo) {
          return false;
        } else {
          const json = await api.getConfigDetail({
            method: 'POST',
            query: {
              identifier: identifier,
              merchantId: merchantInfo.cloudMerchantId,
              storeId: merchantInfo.cloudMerchantStoreId,
              mt: mt
            }
          });
          if (json.data.code === 1000 && json.data.data !== null) {
            let configData = json.data.data;
            let cmsConfigData = {};
            if (this.preview) {
              cmsConfigData = JSON.parse(configData.preview);
            } else {
              cmsConfigData = JSON.parse(configData.content);
              let contents = configData.contents;
              for (let index in contents) {
                let startTime = contents[index].startTime;
                startTime = startTime.substring(0, 19);
                startTime = startTime.replace(/-/g, '/');
                let startTimeTimestamp = new Date(startTime).getTime();
                if (startTimeTimestamp <= new Date().getTime()) {
                  cmsConfigData = JSON.parse(contents[index].content);
                  break;
                }
              }
            }
            let CMSItembanner = cmsConfigData,
              CMSItembannerImage = cmsConfigData[0];
            let imgInfo = {
              url: CMSItembannerImage[0].data.src,
              title: CMSItembannerImage[0].data.title
            };
            return {
              imgInfo
            };
            // that.shareImage = CMSItembannerImage[0].data.src;
            // that.shareTitle = CMSItembannerImage[0].data.title
          }
        }
      },
      checkOrderStatus: async function(orderId) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const payResult = await api.checkOrderStatus({
            header: {
              jwt: customerInfo.jwt
            }
          },
          orderId
        );
      },
      commonssPopupTrack(eventName, eventParams, type, key, ev) {
        let that = this
        let map = {
          TARGET_SALES: {
            EVENT_NOT_INVITED_MEMBER: {
              name: '非受邀提醒弹窗',
              type: 'TS活动'
            },
            EVENT_NOT_STARTED: {
              name: 'TS活动未开始弹窗',
              type: 'TS活动'
            },
            EVENT_HAS_ENDED: {
              name: 'TS活动已结束弹窗',
              type: 'TS活动'
            },
            AUTH_CANCEL: {
              name: '关闭授权手机号弹窗',
              type: 'TS活动'
            },
            AUTH_NOT_INVITED_OLD_MEMBER: {
              name: '非受邀老会员提醒弹窗',
              type: 'TS活动'
            },
            AUTH_NOT_INVITED_NEW_MEMBER: {
              name: '非受邀非会员提醒弹窗',
              type: 'TS活动'
            },
            BIND_MEMBER_NO_ID: {
              name: '注册失败弹窗',
              type: '会员注册/绑定'
            },
            BIND_NOT_MEMBER_NO_ID: {
              name: '注册失败弹窗',
              type: '会员注册/绑定'
            },
            FAIL_NOT_MEMBER: {
              name: 'TS受邀用户注册失败弹窗',
              type: 'TS活动'
            },
            FAIL_NO_ID: {
              name: 'TS受邀用户绑定失败弹窗',
              type: 'TS活动'
            },
            FAIL_HAS_ID: {
              name: 'TS受邀用户绑定失败弹窗',
              type: 'TS活动'
            },
            SUCCESS_JOIN_MESSAGE: {
              name: 'TS非受邀入会成功弹窗',
              type: 'TS活动'
            },
            SUCCESS_BIND_MESSAGE: {
              name: 'TS非受邀绑定成功弹窗',
              type: 'TS活动'
            },
            SUCCESS_JOIN_NEXT: {
              name: 'TS受邀入会成功弹窗',
              type: 'TS活动'
            },
            SUCCESS_BIND_NEXT: {
              name: 'TS受邀绑定成功弹窗',
              type: 'TS活动'
            },
          },
          NORMAL: {
            SUCCESS_BIND: {
              name: 'EB绑定成功弹窗',
              type: '会员注册/绑定'
            },
            SUCCESS_BIND_HAS_MEMBER: {
              name: 'EB绑定成功弹窗',
              type: '会员注册/绑定'
            },
            SUCCESS_JOIN: {
              name: 'EB注册成功弹窗',
              type: '会员注册/绑定'
            },
            FAIL_NO_ID: {
              name: '注册失败弹窗',
              type: '会员注册/绑定'
            },
            FAIL_HAS_ID: {
              name: '注册失败弹窗',
              type: '会员注册/绑定'
            },
            FAIL_NOT_MEMBER: {
              name: '注册失败弹窗',
              type: '会员注册/绑定'
            },
            NONE: {
              name: '入会弹窗',
              type: '会员注册/绑定'
            }
          }
        }
        if (!!that.$commonSensors) {
          if (Object.keys(eventParams).length == 0) {
            let ep = {
              popup_type: map[type][key].type,
              popup_name: map[type][key].name
            }
            let trackEp = Object.assign({}, ep, ev)
            that.$commonSensors.popupEvent(eventName, trackEp)
          } else {
            that.$commonSensors.popupEvent(eventName, eventParams)
          }
        } else {
          if (Object.keys(eventParams).length == 0) {
            let ep = {
              popup_type: map[type][key].type,
              popup_name: map[type][key].name
            }
            let trackEp = Object.assign({}, ep, ev)
            that.$vm.$commonSensors.popupEvent(eventName, trackEp)
          } else {
            that.$vm.$commonSensors.popupEvent(eventName, eventParams)
          }
        }
      },
      commonClTrack(eventName, params, callback) {
        let that = this;
        that.cl_tracker.track(eventName, 'THE MACALLAN EBOUTIQUE麦卡伦', 'wx158a61365a8c8fd6', params, callback);
      },
      cmsClTrack(options) {
        let eventName = options.en;
        let params = options.ep.indexOf("'") !== -1 ? JSON.parse(options.ep.replace(/'/g, '"')) : JSON.parse(options.ep)
        this.commonClTrack(eventName, params);
      },
      getMerchantInfoCommon() {
        return new Promise(async (resolve, reject) => {
          let that = this
          const accountInfo = uni.getAccountInfoSync(); // 小程序appId
          // 获取商户信息
          // let merchantInfo = await api.merchantInfo({
          //   query: {
          //     fetchAk: true
          //   }
          // }, accountInfo.miniProgram.appId);
          let merchantInfo = await api.merchantInfo(accountInfo.miniProgram.appId);
          if (merchantInfo.code == 200) {
            let merchantData = merchantInfo.data;
            // 存储商户信息
            // that.$store.commit('changeApiKeyMap', merchantInfo.data.apiKeyMap)
            uni.setStorageSync(MERCHANT_INFO, merchantData);
            that.globalData.merchantInfo = merchantData
            resolve(merchantInfo.data)
          } else {
            tip.plainText(merchantInfo.data.msg)
            reject(merchantInfo.data)
          }
        })
      },
      compareVersion(v1, v2) {
        // methods是需要点击后需要执行的函数， info是点击需要传的参数
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
          v1.push('0')
        }
        while (v2.length < len) {
          v2.push('0')
        }

        for (let i = 0; i < len; i++) {
          const num1 = parseInt(v1[i])
          const num2 = parseInt(v2[i])

          if (num1 > num2) {
            return 1
          } else if (num1 < num2) {
            return -1
          }
        }

        return 0
      }
    }
  };
</script>

<style>
  @import './static/styles/base.css';
  @import './static/styles/icon.css';
  @import './static/styles/style.css';
  @import './static/styles/iconfont.css';

  @font-face {
    font-family: NotoSansSC-Medium;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Medium.ttf');
  }

  @font-face {
    font-family: NotoSansSC-Regular;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Regular.ttf');
  }

  @font-face {
    font-family: FrankNew-Medium;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Medium.otf');
  }

  @font-face {
    font-family: FrankNew-Regular;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Regular.otf');
  }

  @font-face {
    font-family: Gotham-Medium;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/Gotham/Gotham-Medium.otf');
  }

  @font-face {
    font-family: syht-CN-Light;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/syht-CN/syht-CN-Light.otf');
  }

  @font-face {
    font-family: syht-CN-Regular;
    src: url('https://100000063-1252208446.file.myqcloud.com/fonts/syht-CN/syht-CN-Regular.otf');
  }


  /* 解决头条小程序组件内引入字体不生效的问题 */
  /* #ifdef MP-TOUTIAO */
  /* @font-face {
		font-family: uniicons;
		src: url('/static/uni.ttf');
	} */

  /* #endif */

  .fix-iphonex-bottom {
    bottom: 40rpx !important;
    /* padding-bottom: 40rpx; */
  }

  .fix-iphonex-bottom::after {
    content: ' ';
    position: fixed;
    bottom: 0 !important;
    height: auto !important;
    width: 100%;
    background: #fff;
  }

  .high-light-color {
    color: #ff571a !important;
  }

  .rule-price-box {
    display: flex;
    flex-flow: column wrap;
  }

  .rule-price {
    color: #ff571a;
  }

  .flex-box {
    display: flex;
    flex-flow: row nowrap;
  }

  .flex-column {
    display: flex;
    flex-flow: column nowrap;
  }

  .u-font-24 {
    font-size: 24rpx;
  }

  .u-font-28 {
    font-size: 28rpx;
  }

  .u-font-30 {
    font-size: 30rpx;
  }

  .u-flex-col {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .u-color-1a {
    color: #1a1a1a;
  }

  .u-bg-color {
    background-color: #f7f5f4;
  }

  .u-bg-color-white {
    background-color: #ffffff;
  }

  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    /* overflow-wrap: break-word; */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }

  .ellipsis-two {
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .ellipsis-three {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-wrap: break-word;
    word-break: break-all;
  }

  .ellipsis-four {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    overflow: hidden;
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }

  /*  .fix-iphonex-button {
	  height: 150rpx !important;
  } */
  .ipx-tabbar-height {
    height: 150rpx !important;
  }

  .custom-tab-bottom {
    padding-bottom: 120rpx;
  }

  .custom-tab-bottom-ipx {
    padding-bottom: 150rpx;
  }

  .ios_safe_zone {
    width: 750rpx;
  	height: 64rpx;
  }
  .ios_safe_zone_line {
    width: 750rpx;
    height: 64rpx;
    background-color: #fff;
    position: fixed;
    left: 0;
    bottom:0;
    z-index: 2;
  }
</style>
